package com.example.utils.json;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.example.vo.StudentVO;

import java.util.List;
import java.util.Map;

public class JsonFunction {
    /**
     * JSON字符串转Bean
     */
    public static void jsonToBean() {
        String init = "{\"id\":\"1\",\"age\":25,\"birthDay\":'2021-01-05 12:34:23',\"name\":\"李白\",\"score\":88.5}";
        StudentVO studentVO = JSON.parseObject(init, StudentVO.class);
        System.out.println(studentVO);
    }

    /**
     * JSON字符串转List<Bean>
     */
    public static void jsonToListBean() {
        String init = "[" +
                "{\"id\":\"1\",\"age\":25,\"birthDay\":'2021-01-05 12:34:23',\"name\":\"李白\",\"score\":88.5}," +
                "{\"id\":\"3\",\"age\":22,\"birthDay\":'2022-12-12 12:34:23',\"name\":\"杜甫\",\"score\":90.5}," +
                "]";
        List<StudentVO> list = JSON.parseArray(init, StudentVO.class);
        System.out.println(list);
    }

    /**
     * JSON字符串转Map
     */
    public static void jsonToMap() {
        String init = "{\"id\":\"1\",\"age\":25,\"birthDay\":'2021-01-05 12:34:23',\"name\":\"李白\",\"score\":88.5}";
        Map map = JSON.parseObject(init, Map.class);
        System.out.println(map);
    }

    /**
     * JSON字符串转List<Map>
     */
    public static void jsonToListMap() {
        String init = "[" +
                "{\"id\":\"1\",\"age\":25,\"birthDay\":'2021-01-05 12:34:23',\"name\":\"李白\",\"score\":88.5}," +
                "{\"id\":\"3\",\"age\":22,\"birthDay\":'2022-12-12 12:34:23',\"name\":\"杜甫\",\"score\":90.5}," +
                "]";
        List<Map> mapList = JSONArray.parseArray(init, Map.class);
        System.out.println(mapList);
    }
}
